package com.issc.framework.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;


public final class DataBaseHelper {
    private static final ThreadLocal<Connection> CONNECTION_HOLDER;
    private static final QueryRunner QUERY_RUNNER;
    private static final BasicDataSource DATA_SOURCE;

    static {
        CONNECTION_HOLDER=new ThreadLocal<>();
        QUERY_RUNNER = new QueryRunner();
        String url=ConfigHelper.getJdbcUrl();
        String driver=ConfigHelper.getJdbcDriver();
        String userName=ConfigHelper.getUserName();
        String passWord=ConfigHelper.getPassWord();

        DATA_SOURCE=new BasicDataSource();
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUsername(userName);
        DATA_SOURCE.setPassword(passWord);
    }

    private static Connection getConnection() {
        Connection connection=CONNECTION_HOLDER.get();
        try {
            if (connection == null) {
                connection = DATA_SOURCE.getConnection();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            CONNECTION_HOLDER.set(connection);
        }
        return connection;
    }

    public static void beginTransaction() {
        Connection connection=getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            CONNECTION_HOLDER.set(connection);
        }
    }

    public static void commitTransaction() {
        Connection connection=getConnection();
        if (connection != null) {
            try {
                connection.commit();
                connection.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }

    public static void rollbackTransaction() {
        Connection connection=getConnection();
        if (connection != null) {
            try {
                connection.rollback();
                connection.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }
}
